package com.qxp.simplerpc.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 获取本机ip和host;
 */
@Component
public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> {
    // logger
    private static Logger logger = LoggerFactory.getLogger(ServerConfig.class);

    private int serverPort;

    public String getLocalHost(){
        try {
            InetAddress address = InetAddress.getLocalHost();
            return address.getHostAddress();
        } catch (UnknownHostException e) {
           logger.error("未知的本机地址",e);
        }
        return "UnknownHost";

    }

    public int getServerPort() {
        return serverPort;
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();
    }
}
